package gqz.mvvm.view.custom;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/12/13.
 */

public class PickerView extends ScrollView {

    String TAG = "PickerView---";

    int width = 500, height = 800, halfW, halfH;
    int mTextHeight;
    float mTextSize = 25;
    int visibleItemCount = 3;
    int itemH;

    Context context;
    Paint paint;

    ArrayList<String> strlist = new ArrayList<>();
    HashMap<Integer, Integer> posMap = new HashMap<>();

    public PickerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOverScrollMode(OVER_SCROLL_NEVER);//设置ScrollView滑动到极限的时候不显示提示（就是那个阴影）
//        setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
        setVerticalScrollBarEnabled(false);//隐藏滚动条
        this.context = context;
        initPaint();
        init();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(2);
        paint.setTextSize(30);
    }

    private void init() {
        float mDensity = getResources().getDisplayMetrics().density;
        mTextHeight = (int) ((mDensity + 1) * mTextSize);

        strlist.clear();
        for (int i = 0; i < 100; i++) {
            strlist.add("Itemgj" + i);
            posMap.put(i, i * mTextHeight * 2);
        }

        Log.v(TAG, "all text height:" + (100 * mTextHeight * 2));

        /**
         * 初始化数据,首先添加Group
         */
        LinearLayout mTextGroup = new LinearLayout(context);
        mTextGroup.setOrientation(LinearLayout.VERTICAL);
        mTextGroup.setGravity(Gravity.CENTER);
        mTextGroup.setLayoutParams(new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT));
        addView(mTextGroup);

        mTextGroup.addView(createTextView(""));
        for (int i = 0; i < strlist.size(); i++) {
            mTextGroup.addView(createTextView("" + strlist.get(i)));
//            mTextGroup.addView(createDivider());
        }
        mTextGroup.addView(createTextView(""));

        setBackground(new Drawable() {
            @Override
            public void draw(Canvas canvas) {
                /**
                 * 这里把两条线之间的距离设置为了两个TextView的高度
                 */
                canvas.drawLine(
                        width * 0.1f,
                        height / 2 - mTextHeight,
                        width * 0.9f,
                        height / 2 - mTextHeight,
                        paint
                );
                canvas.drawLine(
                        width * 0.1f,
                        height / 2 + mTextHeight,
                        width * 0.9f,
                        height / 2 + mTextHeight,
                        paint
                );
                /*int pos = getScrollY();
                canvas.drawText(pos + "", width - 150, 30, paint);
                int size = posMap.size();*/
                /*for (int i = 0; i < size; i++) {
                    if (i + 1 >= size) break;
                    int pos1 = posMap.get(i), pos2 = posMap.get(i + 1);
                    if (pos1 < pos && pos < pos2) {//在i的范围里
                        int centerline = (pos2 - pos1) / 2 + pos1;
                        if (pos < centerline) {//滚到上一个
                            canvas.drawText("上", width - 50, 30, paint);
                        } else if (centerline <= pos) {//滚到下一个
                            canvas.drawText("下", width - 50, 30, paint);
                        }
                        break;
                    }
                }*/
            }

            @Override
            public void setAlpha(int i) {

            }

            @Override
            public void setColorFilter(ColorFilter colorFilter) {

            }

            @Override
            public int getOpacity() {
                return PixelFormat.UNKNOWN;
            }
        });
    }

    /**
     * 动态创建TextView
     */
    private TextView createTextView(String s) {
        TextView tv = new TextView(context);
        tv.setText(s);
        tv.setTextColor(getResources().getColor(android.R.color.black));
        tv.setTextSize(mTextSize);
        tv.setGravity(Gravity.CENTER);
//        tv.setBackgroundColor(Color.rgb(0xee, 0xee, 0xee));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mTextHeight);
        params.bottomMargin = mTextHeight / 2;
        params.topMargin = mTextHeight / 2;
        tv.setLayoutParams(params);
        return tv;
    }

    private View createDivider() {
        View view;
        view = new View(context);
        view.setBackgroundColor(getResources().getColor(android.R.color.black));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
        view.setLayoutParams(params);
        return view;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        height = mTextHeight * visibleItemCount * 2;

        width = getMeasureSize(widthMeasureSpec, width);
        height = getMeasureSize(heightMeasureSpec, height);

        halfW = width / 2;
        halfH = height / 2;

        setMeasuredDimension(width, height);
    }

    private int getMeasureSize(int measureSpec, int defaultSize) {
        int result = 0;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        if (mode == MeasureSpec.EXACTLY) {
            result = size;
        } else {
            result = defaultSize;
        }

        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /*for (int i = 0; i < posMap.size(); i++) {
            int pos = posMap.get(i);
            canvas.drawText(pos + "", 10, pos, paint);
            canvas.drawLine(0, pos, width, pos, paint);
        }*/
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 2);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
                handler.sendEmptyMessageDelayed(0, 100);
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void scrollToPosition(int y) {
        ObjectAnimator yTranslate = ObjectAnimator.ofInt(this, "scrollY", y);
        yTranslate.setDuration(500);
        yTranslate.setInterpolator(new DecelerateInterpolator());
        yTranslate.start();
    }

    int lastY = 0;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (lastY == getScrollY()) {
                        Log.d(TAG, "fling stop!");
                        //
                        int size = posMap.size();
                        for (int i = 0; i < size; i++) {
                            if (i + 1 >= size) break;
                            int pos1 = posMap.get(i), pos2 = posMap.get(i + 1);
                            if (pos1 < lastY && lastY < pos2) {//在i的范围里
                                int centerline = (pos2 - pos1) / 2 + pos1;
                                if (lastY < centerline) {//滚到上一个
                                    scrollToPosition(pos1);
                                } else if (centerline <= lastY) {//滚到下一个
                                    scrollToPosition(pos2);
                                }
                                break;
                            }
                        }
                    } else {
                        handler.sendEmptyMessageDelayed(0, 15);
                        lastY = getScrollY();
                    }
                    break;
            }
            return false;
        }
    });
}
